package com.windsea.relationshipmining.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.windsea.relationshipmining.R;
import com.windsea.relationshipmining.api.ContactApi;
import com.windsea.relationshipmining.database.DBUserData;

public class UserInfoActivity extends Activity implements
		android.view.View.OnClickListener {
	EditText etName, etEmail, etAge, etPhone;
	Button btnSave;
	DBUserData dbUserData;
	String name, email, age, job, gender, phone, result;
	RadioGroup rdGroup, rdGroup2;
	RadioButton studentRB, employeeRB, genderRB;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		dbUserData = new DBUserData(getBaseContext());
		dbUserData.open();
		setContentView(R.layout.activity_user_info);
		etName = (EditText) findViewById(R.id.editTextName);
		etEmail = (EditText) findViewById(R.id.editTextEmail);
		etAge = (EditText) findViewById(R.id.editTextAge);
		etPhone = (EditText) findViewById(R.id.editTextPhone);
		etName.setHint("Barack Obama");
		etEmail.setHint("obama@gmail.com");
		etAge.setHint("52");
		rdGroup = (RadioGroup) findViewById(R.id.radioGroupJ);
		rdGroup2 = (RadioGroup) findViewById(R.id.radioGroupG);
		btnSave = (Button) findViewById(R.id.btnSave);
		btnSave.setOnClickListener(this);
		Intent callerIntent = getIntent();
		Bundle packageFromCaller = callerIntent.getBundleExtra("UserInfo");
		result = packageFromCaller.getString("Info");

		if (result.equals("edit")) {
			Cursor curInfo = dbUserData.getInfo();
			if (curInfo != null && curInfo.moveToFirst()) {
				name = curInfo.getString(curInfo.getColumnIndex("Name"));
				email = curInfo.getString(curInfo
						.getColumnIndex("Emailaddress"));
				age = curInfo.getString(curInfo.getColumnIndex("Age"));
				job = curInfo.getString(curInfo.getColumnIndex("Job"));
				gender = curInfo.getString(curInfo.getColumnIndex("Gender"));
				phone = curInfo
						.getString(curInfo.getColumnIndex("Phonenumber"));
				etName.setText(name);
				etEmail.setText(email);
				etAge.setText(age);
				etPhone.setText(phone);
				if (job.equals("student")) {
					rdGroup.check(R.id.studentRBtn);
				} else {
					rdGroup.check(R.id.employeeRBtn);
				}
				if (gender.equals("man")) {
					rdGroup2.check(R.id.manBtn);
				} else {
					rdGroup2.check(R.id.womanRBtn);
				}
			}

		}
		dbUserData.close();
	}

	@Override
	public void onClick(View v) {
		if (v == btnSave) {
			name = etName.getText().toString();
			email = etEmail.getText().toString();
			age = etAge.getText().toString();
			phone = etPhone.getText().toString();

			switch (rdGroup.getCheckedRadioButtonId()) {
			case R.id.studentRBtn:
				job = "student";
				break;
			case R.id.employeeRBtn:
				job = "employee";
				break;

			default:
				job = "unknown";
				break;
			}

			switch (rdGroup2.getCheckedRadioButtonId()) {
			case R.id.manBtn:
				gender = "man";
				break;
			case R.id.womanRBtn:
				gender = "woman";
				break;

			default:
				gender = "woman";
				break;
			}
			int d = 0;
			try {
				name.charAt(0);
				d++;
				email.charAt(0);
				d++;
				age.charAt(0);
				d++;
				phone.charAt(0);
				d++;
				if (Integer.parseInt(age) < 10) {
					age = null;
					Integer.parseInt(age);
				} else if (Integer.parseInt(age) > 60) {
					age = null;
					Integer.parseInt(age);
				}
				if (!isEmailValid(email)) {
					etEmail.setError("Email không hợp lệ");
				} else {

					dbUserData.open();
					if (result.equals("insert")) {
						dbUserData.insertInfo(name, email, age, job, gender,
								getDeviceID(), phone);
						Log.i("UserInfo", name);
					} else {
						dbUserData.updateInfo(name, email, age, job, gender,
								phone);
					}
					dbUserData.close();

					finish();

					Intent intent = new Intent(getBaseContext(),
							HelpActivity.class);
					startActivity(intent);

				}
			} catch (StringIndexOutOfBoundsException stre) {
				if (d == 0)
					etName.setError("Chưa điền tên");
				else if (d == 1)
					etEmail.setError("Chưa điền email");
				else if (d == 2) {
					etAge.setError("Chưa điền tuổi");
				} else {
					etPhone.setError("Chưa điền số điện thoại");
				}
			} catch (NumberFormatException e) {
				etAge.setError("Tuổi phải từ 10 đến 60 tuổi");
			}

		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if ((keyCode == KeyEvent.KEYCODE_BACK)) {
			finish();
			Intent intent = new Intent(getBaseContext(), MainActivity.class);
			startActivity(intent);
		}
		return super.onKeyDown(keyCode, event);
	}

	/**
	 * This method gets a device ID.
	 * 
	 * @return The device ID.
	 */
	private String getDeviceID() {
		TelephonyManager tm = (TelephonyManager) getBaseContext()
				.getSystemService(Context.TELEPHONY_SERVICE);
		return tm.getDeviceId();
	}

	private String getDevicePhonenumber() {
		TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
		return ContactApi.phoneNumberProcess(tm.getLine1Number());
	}

	boolean isEmailValid(CharSequence email) {
		return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
	}
}
